package com.example.text2.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.example.text2.R;
import com.example.text2.adapter.RlvAdapter;
import com.example.text2.bean.Bean;
import com.example.text2.http.Api;
import com.example.text2.moudle.Moudle;
import com.example.text2.presenter.Presenter;
import com.example.text2.view.View;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class BoonFragment extends Fragment implements View {


    @BindView(R.id.rlv)
    XRecyclerView mRlv;
    private View view;
    private Unbinder unbinder;
    private int count=10;
    RlvAdapter mRlvAdapter;

    public BoonFragment() {
        // Required empty public constructor
    }


    @Override
    public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container,
                                          Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        android.view.View inflate = inflater.inflate(R.layout.fragment_boon, container, false);
        data();
        unbinder = ButterKnife.bind(this, inflate);

        final ArrayList<Bean.ResultsBean> list = new ArrayList<>();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 3);
        mRlv.setLayoutManager(gridLayoutManager);
        mRlvAdapter = new RlvAdapter(list,getContext());
        mRlv.setAdapter(mRlvAdapter);
        mRlv.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                list.clear();
                data();
                mRlv.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                count+=10;
                data();
            }
        });
        return inflate;
    }

    private void data() {
        Presenter presenter = new Presenter(new Moudle(), this);
        presenter.getData(count,Api.BOON);
    }

    @Override
    public void showSuccess(Object o, Api api) {
        String s= (String) o;
        Log.e("duan", "showSuccess: "+s );
        Gson gson = new Gson();
        Bean bean = gson.fromJson(s, Bean.class);
        List<Bean.ResultsBean> list = bean.getResults();
        if (list.size()>0){
            mRlvAdapter.addData(list);
        }
        mRlv.loadMoreComplete();
    }

    @Override
    public void showError(String error) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
